<template>
  <!-- 地图容器，id 用于地图初始化挂载 -->
  <div id="mapContainer">
    
    <!-- 地图工具栏 -->
    <div class="map-utils">
      <div class="user-tool">
        <!-- 画点按钮，点击后激活 marker 工具 -->
        <button class="btn btn-success" @click.stop="activate('marker')">
          画点
        </button>
        <!-- 画线按钮，点击后激活 polyline 工具 -->
        <button class="btn btn-success" @click.stop="activate('polyline')">
          画线
        </button>
        <!-- 画圆按钮，点击后激活 circle 工具 -->
        <button class="btn btn-success" @click.stop="activate('circle')">
          画圆
        </button>
        <!-- 画矩形按钮，点击后激活 rectangle 工具 -->
        <button class="btn btn-success" @click.stop="activate('rectangle')">
          画矩形
        </button>
        <!-- 多边形按钮，点击后激活 polygon 工具 -->
        <button class="btn btn-success" @click.stop="activate('polygon')">
          多边形
        </button>
        <!-- 测距 -->
        <button class="btn btn-success" @click.stop="ranging">
          测距
        </button>
        <!-- 清除点线面这种按钮  测距按钮需要手动清除 -->
        <button class="btn btn-success" @click.stop="handleClear">
          清除
        </button>

        <button class="btn btn-success" @click.stop="measureArea">
          测面积
        </button>

        <!-- Marker 功能按钮组 -->
        <div class="marker-buttons-group">
          <button class="btn btn-info" @click.stop="addMarkerAtPosition(28.233838, 112.999839)">
            添加标记
          </button>
          <button class="btn btn-info" @click.stop="addCustomMarker(28.234838, 113.000839, '/src/assets/images/default-drone.png')">
            自定义图标
          </button>
          <button class="btn btn-info" @click.stop="addMarkerWithPopup(28.235838, 113.001839, '<h3>测试标记</h3><p>这是一个带弹窗的标记</p>')">
            弹窗标记
          </button>
          <button class="btn btn-info" @click.stop="addMultipleMarkers">
            批量添加
          </button>
          <button class="btn btn-warning" @click.stop="toggleClickToAddMarker">
            {{ clickToAddMarker ? '关闭点击添加' : '开启点击添加' }}
          </button>
        </div>

        <button class="btn btn-success" @click.stop="showMapTypePanel = !showMapTypePanel">
          图层切换
        </button>
        <div v-if="showMapTypePanel" class="map-type-panel" @click.stop>
          <div class="map-type-item" v-for="item in mapTypes" :key="item.type" @click="switchMapType(item.type)">
            {{ item.label }}
          </div>
        </div>
        <button class="btn btn-success" @click.stop="toggleFillColorPanel">
          设置填充颜色
        </button>
        <div v-if="showFillColorPanel" class="fill-color-panel" @click.stop style="position:absolute;right:120px;top:220px;z-index:2000;background:#fff;padding:16px 24px;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,0.15);">
          <label style="margin-right:8px;">选择颜色：</label>
          <input type="color" v-model="fillColor" @input="onFillColorChange" style="width:40px;height:40px;border:none;vertical-align:middle;" />
          <span style="margin-left:12px;vertical-align:middle;">{{ fillColor }}</span>
          <button class="btn btn-success" style="margin-left:16px;" @click="showFillColorPanelEntry">确定</button>
        </div>

        <button class="btn btn-success" @click.stop="flyTo">
          定位
        </button>
        <!-- 其他按钮已注释，如需可取消注释使用 -->
      </div>
      <!-- 工具栏容器结束 -->
  </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
// @ts-ignore
import mapUtils from "@/utils/mapUtils/index.js"

// 定义地图工具类接口
interface MapUtils {
  initMap: () => void
  addMarker: () => void
  addMarkerAtPosition: (lat: number, lng: number, options?: any) => any
  addMarkers: (markersData: any[]) => any[]
  addCustomMarker: (lat: number, lng: number, iconUrl: string, options?: any) => any
  addMarkerWithPopup: (lat: number, lng: number, popupContent: string, options?: any) => any
  enableClickToAddMarker: () => void
  disableClickToAddMarker: () => void
  disableDraw: () => void
  clearMeasureOnly: () => void
  setActiveTool: (tool: string) => void
  initActivate: (tool: string) => void
  addRanging: () => void
  clearAll: () => void
  switchMapType: (type: string) => void
  setDrawColor: (color: { fillColor: string }) => void
  addPolygon: (latlngs: number[][], options: { fillColor: string }) => void
  CalculatePolygonArea: (latlngs: any[]) => number
  openTooltip: (latlngs: any[], color: string, text: string) => void
  map?: any
  fillColor?: string
}

// 定义Props接口
interface Props {
  coords?: Array<{ lat: number; lng: number }>
  areaColor?: string
}

// 声明全局BM对象
declare global {
  interface Window {
    BM: any
  }
}

// 定义Props
const props = withDefaults(defineProps<Props>(), {
  coords: () => [],
  areaColor: '#ff000088'
})

// 定义Emits
const emit = defineEmits<{
  changePolygonCoords: [coords: any[]]
  changeColor: [color: string]
}>()

// 响应式数据
const mapUtile = ref<MapUtils | null>(null) // 地图实例对象
const activeTool = ref<string | null>(null) // 当前激活的绘图工具类型
const coordsList = ref<any[]>([]) // 经纬度坐标集合
const showMapTypePanel = ref(false) // 控制地图类型面板显示
const showFillColorPanel = ref(false) // 控制填充颜色弹窗显示
const fillColor = ref('#ff000088') // 默认填充色
const mapReady = ref(false) // 地图初始化完成标志
const clickToAddMarker = ref(false) // 控制是否开启点击添加marker功能

// 地图类型配置
const mapTypes = reactive([
        { label: '卫星地图', type: 'bigemap.satellite' },
        { label: '电子地图', type: 'bigemap.streets' },
        { label: '地形地图', type: 'bigemap.terrain' },
        { label: '默认地图', type: 'bigemap.2i5fd1il' },
])

// 选择颜色传递给父组件
const handleCoordsAndColorEcho = () => {
  // 回显多边形和颜色
  if (!mapReady.value) return;
  if (mapUtile.value) {
    mapUtile.value.clearAll();
    if (Array.isArray(props.coords) && props.coords.length > 2) {
      const latlngs = props.coords.map(pt => [pt.lat, pt.lng]);
      // 使用 mapUtils 的 addPolygon 方法
      if (typeof mapUtile.value.addPolygon === 'function') {
        mapUtile.value.addPolygon(latlngs, { fillColor: fillColor.value });
      } else if (mapUtile.value.map && window.BM && typeof window.BM.polygon === 'function') {
        // 兜底
        window.BM.polygon(latlngs, { fillColor: fillColor.value }).addTo(mapUtile.value.map);
      }
    }
    // 同步颜色到工具类
    if (typeof mapUtile.value.setDrawColor === 'function') {
      mapUtile.value.setDrawColor({ fillColor: fillColor.value });
    } else {
      mapUtile.value.fillColor = fillColor.value;
    }
  }
}

// 监听props变化
watch(() => props.coords, () => {
  handleCoordsAndColorEcho()
}, { deep: true, immediate: true })

watch(() => props.areaColor, (newColor) => {
  console.log(newColor)
  fillColor.value = newColor
  handleCoordsAndColorEcho()
}, { immediate: true })

// 生命周期钩子
onMounted(() => {
    // 组件挂载后初始化地图
  initMap()
    // 点击空白处关闭地图类型面板
  document.addEventListener('click', handleDocumentClick)
    // 地图初始化后，手动触发一次回显
  nextTick(() => {
      setTimeout(() => {
      mapReady.value = true
      handleCoordsAndColorEcho()
         // 测试自动绘制指定多边形
      // const coordsData = [
        //   [
        //     { lat: 28.234608295004463, lng: 113.0006128549576 },
        //     { lat: 28.234698043133207, lng: 113.00168573856355 },
        //     { lat: 28.234093422701775, lng: 113.001047372818 },
        //     { lat: 28.234088699091167, lng: 113.00104200839998 }
        //   ]
        // ];
        // const latlngs = coordsData[0].map(pt => [pt.lat, pt.lng]);
      // if (mapUtile.value && typeof mapUtile.value.addPolygon === 'function') {
      //   mapUtile.value.addPolygon(latlngs, { fillColor: '#ff000088' });
      // }
    }, 300) // 延迟确保地图已初始化
  })
})

onBeforeUnmount(() => {
  document.removeEventListener('click', handleDocumentClick)
})

    // 初始化地图方法
const initMap = () => {
  console.log('开始初始化地图...')
  console.log('BM对象是否存在:', typeof window.BM !== 'undefined')
  console.log('mapUtils是否存在:', typeof mapUtils !== 'undefined')
  
  try {
    mapUtile.value = new mapUtils(
        "mapContainer",
        "bigemap.2i5fd1il",
        {
          accessToken:
            "pk.eyJ1IjoiY3VzX2EwNnk4MHEyIiwiYSI6IjM0b3UybnJmNjhmazJ6aHByeGVrOHJnMDYifQ.5V9X7RXaZ4JdcvnV0ctnwA", // 地图访问令牌
          httpUrl: "http://192.168.110.210:3000", // 地图服务地址
          zoom: 18, // 初始缩放级别
          center: [28.233838, 112.999839], // 地图中心点坐标
        //   fitBounds: [
        //     [28.21055793762207, 112.98915100097656],
        //     [28.256534576416016, 113.05103302001953],
        //   ],
        },
      handleMapEvent // 传递事件回调
    ) as MapUtils;
    
    console.log('mapUtils实例创建成功:', mapUtile.value)
    
    if (mapUtile.value && typeof mapUtile.value.initMap === 'function') {
      try {
        mapUtile.value.initMap();
        console.log('地图初始化完成')
        console.log('地图实例:', mapUtile.value.map)
        console.log('地图容器元素:', document.getElementById('mapContainer'))
        addMarker()
      } catch (error) {
        console.error('地图初始化过程中出错:', error)
      }
    } else {
      console.error('mapUtils实例或initMap方法不存在')
    }
  } catch (error) {
    console.error('地图初始化失败:', error)
  }
}

    // 统一处理地图事件并输出坐标和类型
const handleMapEvent = (event: any) => {
      if (event.type === 'click') {
        // console.log('【Vue打印】地图点击坐标:', event.coords);
      } else if (event.type === 'draw') {
    coordsList.value = event.coords
    console.log('经纬度坐标:', coordsList.value)
    emit("changePolygonCoords", coordsList.value)
        // 测面积模式下，绘制多边形后自动计算面积
    if (activeTool.value === 'measureArea' && event.drawType === 'polygon') {
          // event.coords 可能是多边形点数组
          let latLngs = event.coords;
          // 兼容嵌套数组
          if (Array.isArray(latLngs) && Array.isArray(latLngs[0])) latLngs = latLngs[0];
      if (latLngs && latLngs.length > 2 && mapUtile.value && typeof mapUtile.value.CalculatePolygonArea === 'function') {
        const area = mapUtile.value.CalculatePolygonArea(latLngs);
            let areaStr = area > 1000000 ? (area/1000000).toFixed(2) + ' 平方公里' : area.toFixed(2) + ' 平方米';
            // window.alert('测量面积：' + areaStr);
        mapUtile.value.openTooltip(latLngs,'red',areaStr)
          }
          // 退出测面积模式
      activeTool.value = null;
        }
        // 关键：无论什么类型，绘制完成后都禁用
    if (mapUtile.value && typeof mapUtile.value.disableDraw === 'function') {
      mapUtile.value.disableDraw();
    }
        }
      }


    // 添加marker方法，调用地图实例的 addMarker
const addMarker = () => {
  mapUtile.value?.addMarker();
}

    // 在指定位置添加 marker
const addMarkerAtPosition = (lat: number, lng: number, options = {}) => {
  return mapUtile.value?.addMarkerAtPosition(lat, lng, options);
}

    // 批量添加 markers
const addMarkers = (markersData: any[]) => {
  return mapUtile.value?.addMarkers(markersData);
}

    // 添加带自定义图标的 marker
const addCustomMarker = (lat: number, lng: number, iconUrl: string, options = {}) => {
  return mapUtile.value?.addCustomMarker(lat, lng, iconUrl, options);
}

    // 添加带弹窗的 marker
const addMarkerWithPopup = (lat: number, lng: number, popupContent: string, options = {}) => {
  return mapUtile.value?.addMarkerWithPopup(lat, lng, popupContent, options);
}

    // 批量添加多个markers的示例方法
const addMultipleMarkers = () => {
      const markersData = [
        { 
          lat: 28.233838, 
          lng: 112.999839, 
          options: { title: '标记点1', draggable: true } 
        },
        { 
          lat: 28.234838, 
          lng: 113.000839, 
          options: { title: '标记点2', draggable: true } 
        },
        { 
          lat: 28.235838, 
          lng: 113.001839, 
          options: { title: '标记点3', draggable: true } 
        },
        { 
          lat: 28.236838, 
          lng: 113.002839, 
          options: { title: '标记点4', draggable: true } 
        }
      ];
      
  const markers = addMarkers(markersData);
  console.log('批量添加了', markers?.length || 0, '个标记');
      return markers;
}

    // 切换点击添加marker功能
const toggleClickToAddMarker = () => {
  clickToAddMarker.value = !clickToAddMarker.value;
      
  if (clickToAddMarker.value) {
        // 开启点击添加功能
    mapUtile.value?.enableClickToAddMarker();
        console.log('已开启点击添加marker功能');
      } else {
        // 关闭点击添加功能
    mapUtile.value?.disableClickToAddMarker();
        console.log('已关闭点击添加marker功能');
      }
}

    // 激活绘图工具，调用地图实例的 initActivate 方法
const activate = (e: string) => {
  if (mapUtile.value && typeof mapUtile.value.disableDraw === 'function') {
    mapUtile.value.disableDraw();
      }
      // 清理测距相关内容
  if (mapUtile.value && typeof mapUtile.value.clearMeasureOnly === 'function') {
    mapUtile.value.clearMeasureOnly();
      }
      // 关闭点击添加marker功能
  if (clickToAddMarker.value) {
    clickToAddMarker.value = false;
    mapUtile.value?.disableClickToAddMarker();
  }
  activeTool.value = e;
  mapUtile.value?.setActiveTool && mapUtile.value.setActiveTool(e);
  mapUtile.value?.initActivate(e);
}

// 测距
const ranging = () => {
  if (mapUtile.value && typeof mapUtile.value.disableDraw === 'function') {
    mapUtile.value.disableDraw();
      }
      // 关闭点击添加marker功能
  if (clickToAddMarker.value) {
    clickToAddMarker.value = false;
    mapUtile.value?.disableClickToAddMarker();
  }
  mapUtile.value?.addRanging()
}

    // 测面积
const measureArea = () => {
  if (mapUtile.value && typeof mapUtile.value.disableDraw === 'function') {
    mapUtile.value.disableDraw();
      }
      // 清理测距相关内容
  if (mapUtile.value && typeof mapUtile.value.clearMeasureOnly === 'function') {
    mapUtile.value.clearMeasureOnly();
      }
      // 关闭点击添加marker功能
  if (clickToAddMarker.value) {
    clickToAddMarker.value = false;
    mapUtile.value?.disableClickToAddMarker();
  }
  activeTool.value = 'measureArea';
  if (mapUtile.value && typeof mapUtile.value.setActiveTool === 'function') {
    mapUtile.value.setActiveTool('measureArea');
  }
  if (mapUtile.value && typeof mapUtile.value.initActivate === 'function') {
    mapUtile.value.initActivate('polygon');
  }
}

// 清除
const handleClear = () => {
  if (mapUtile.value && typeof mapUtile.value.clearAll === 'function') {
    mapUtile.value.clearAll();
  }
}

    // 切换底图
const switchMapType = (type: string) => {
  showMapTypePanel.value = false;
  if (mapUtile.value && typeof mapUtile.value.switchMapType === 'function') {
    mapUtile.value.switchMapType(type);
  }
}

const handleDocumentClick = () => {
  showMapTypePanel.value = false;
}

const toggleFillColorPanel = () => {
  showFillColorPanel.value = !showFillColorPanel.value;
}

const showFillColorPanelEntry = () => {
  showFillColorPanel.value = false
  emit('changeColor', fillColor.value)
}

const onFillColorChange = () => {
      // 颜色选择后，保存到 fillColor，并同步到地图工具类
  if (mapUtile.value) {
        // 你可以根据地图工具类的实际方法来设置颜色
    if (typeof mapUtile.value.setDrawColor === 'function') {
      mapUtile.value.setDrawColor({ fillColor: fillColor.value });
        } else {
          // 兜底：直接赋值
      mapUtile.value.fillColor = fillColor.value;
    }
  }
}

// 定位
const flyTo = (position?: any) => {
      const defaultPos = [28.233838, 112.999839];
      let target = defaultPos;
      if (position) {
        if (Array.isArray(position)) {
          target = position;
        } else if (position.lat !== undefined && position.lng !== undefined) {
          target = [position.lat, position.lng];
        }
      }
  if (mapUtile.value && mapUtile.value.map) {
    mapUtile.value.map.flyTo(target, 18); // 18为缩放级别，可根据需要调整
      } else {
        console.warn('地图未初始化');
      }
    }
</script>

<style scoped>
/* 地图容器样式，设置全屏显示 */
#mapContainer {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 500px; /* 确保最小高度 */
  overflow: hidden;
  background-color: #f0f0f0; /* 临时背景色，用于调试 */
  border: 2px solid #ccc; /* 临时边框，用于调试 */
}

/* 工具栏样式，定位在右上角 */
.map-utils {
  display: none;
  position: absolute;
  right: 20px;
  top: 20px;
  z-index: 999;
}

/* 工具栏按钮样式 */
.map-utils-item {
  padding: 10px;
  background-color: pink;
}

/* 激活状态按钮样式 */
.map-utils-item.active {
  background-color: #ffb6c1; /* 高亮色 */
  font-weight: bold;
}

/* 工具栏按钮排列为纵向 */
.user-tool {
  display: flex;
  flex-direction: column;
}

/* 按钮基础样式 */
.btn {
  display: inline-block;
  padding: 6px 12px;
  margin-bottom: 10px;
  font-size: 14px;
  font-weight: 400;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-image: none;
  border: 1px solid transparent;
  border-radius: 4px;
}

.map-type-panel {
  position: absolute;
  top: 160px;
  right: auto;
  left: -130px; /* 向左偏移，确保在按钮左侧显示，可根据实际宽度微调 */
  background: #fff;
  border: 1px solid #eee;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  z-index: 1000;
  min-width: 120px;
  border-radius: 4px;
  padding: 8px 0;
}
.map-type-item {
  padding: 8px 16px;
  cursor: pointer;
  transition: background 0.2s;
}
.map-type-item:hover {
  background: #f5f5f5;
}

/* 删除按钮样式 */
::v-deep .delete-graphic-btn {
  /* 让按钮始终在地图上方且不遮挡鼠标操作 */
  z-index: 2000;
  pointer-events: auto;
}
::v-deep .delete-graphic-btn span {
  display: inline-block;
  width: 22px;
  height: 22px;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 1px 4px #aaa;
  line-height: 22px;
  text-align: center;
  color: #f56c6c;
  font-size: 16px;
  cursor: pointer;
  border: 1px solid #f56c6c;
  transition: background 0.2s, color 0.2s;
}
::v-deep .delete-graphic-btn span:hover {
  background: #f56c6c;
  color: #fff;
}


::v-deep .bigemap-touch .bigemap-bar-part-top-and-bottom {
    display: none !important;
}

::v-deep .bigemap-bar a{
    display: none !important;
}

.fill-color-panel{
  width: 250px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* Marker 按钮组样式 */
.marker-buttons-group {
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
  padding: 8px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 6px;
  border: 1px solid #ddd;
}

.marker-buttons-group .btn {
  margin-bottom: 5px;
  font-size: 12px;
  padding: 4px 8px;
}

.marker-buttons-group .btn:last-child {
  margin-bottom: 0;
}
</style>


